import re
from urllib import request
# 自定义类
class Spider():

    # 需要爬取数据的url路径
    url = 'https://www.panda.tv/cate/lol'

    # 使用正则抓取需要的数据 添加？是非贪婪模式 获取（）内的内容
    root_pattern = '<div class="baseVideo-info">([\s\S]*?)</div>'
    name_pattern = '</i>([\s\S]*?)</span>'
    number_pattern = '<span class="baseVideo-number">([\s\S]*?)</span>'

    # 创建私有方法
    def __fetch_content(self):
        r = request.urlopen(Spider.url)
        htmls = r.read()#bytes
        htmls = str(htmls,encoding='utf-8')
        return htmls

    def __anylysis(self,htmls):
        root_html = re.findall(Spider.root_pattern,htmls)
        anchors = []
        for html in root_html:
            name = re.findall(Spider.name_pattern,html)
            number = re.findall(Spider.number_pattern,html)
            anchor = {'name':name,'number':number}
            anchors.append(anchor)
        return anchors

    def __refine(self,anchors):

        # strip()内置函数，去除前后的空格换行符号
        l = lambda anchor: {
            'name':anchor['name'][0].strip(),
            'number':anchor['number'][0]
            }
        return map(l,anchors)

    def __sort(self,anchors):
        anchors = sorted(anchors,key=self.__sort_seed,reverse=True)
        return anchors

    # 比较
    def __sort_seed(self,anchor):
        r = re.findall('\d*',anchor['number'])
        number = float(r[0])
        if '万' in anchor['number']:
            number *= 10000
        return number
    
    def __show(self,anchors):
        print('python3抓取熊猫lol直播人气排名！')
        for rank in range(0,len(anchors)):
            print('名次->' + str(rank + 1) + ':' + anchors[rank]['name'] + 
            '  ' + anchors[rank]['number'])

    # 入口方法
    def go(self):
        htmls = self.__fetch_content()
        anchors = self.__anylysis(htmls)
        anchors = list(self.__refine(anchors))
        anchors = self.__sort(anchors)
        self.__show(anchors)

spider = Spider()
spider.go()